package com.by.service.impl;

import com.by.bean.CustomerInquiry;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.utils.Assert;
import com.by.common.utils.DateUtils;
import com.by.mapper.CustomerInquiryDetailMapper;
import com.by.mapper.CustomerInquiryMapper;
import com.by.service.CustomerInquiryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CustomerInquiryServiceImpl extends BaseServiceImpl<CustomerInquiry, CustomerInquiryMapper> implements CustomerInquiryService {

    String maxCode;//最大编码

    @Autowired
    CustomerInquiryDetailMapper detailMapper;

    @Transactional
    @Override
    public int save(CustomerInquiry entity) {
        //1.生成编码
        entity.setCode(generateNewCode());
        //2.保存询价单
        int rs = baseMapper.save(entity);
        Assert.isZero(rs, "保存询价单失败");
        //3.保存询价明细
        if (null != entity.getCustomerInquiryDetails() && entity.getCustomerInquiryDetails().size() > 0) {
            //批量保存
            rs = detailMapper.batchSave(entity.getId(), entity.getCustomerInquiryDetails());
            Assert.isZero(rs, "保存询价单明细失败");
        }
        return 1;
    }

    /**
     * 产生新的编码
     *
     * @return
     */
    String generateNewCode() {
        //获取年月
        String ym = DateUtils.getSystemTimeYM();
        //判断最大编码是否存在
        if (null == maxCode) {
            //如果不存在  查询数据库
            maxCode = baseMapper.queryMaxCode();
            //如果当前没有编码  说明当前的询价单是当月第一笔
            if (null == maxCode) {
                //产生新的编码
                maxCode = "XJ" + ym + "0001";
                return maxCode;
            }
        }

        //执行到这里  获取最大编码 XJ25020001  计算新的编码
        //提取编码中的日期  2502
        String tmpYm = maxCode.substring(2, 6);
        if (!ym.equals(tmpYm)) {
            //说明当前最大编码不是当月的编码
            maxCode = "XJ" + ym + "0001";
            return maxCode;
        }

        //如果到这里 是当月的最大编码  序号累加 XJ25020001
        String prefix = maxCode.substring(0, 6);
        String seq = maxCode.substring(6);
        int num = Integer.parseInt(seq);
        num++;
        maxCode = prefix + String.format("%04d", num);
        return maxCode;
    }
}
